package view;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class View {
    public HttpServlet servlet;
    public ServletContext application;
    public HttpServletRequest request;
    public HttpServletResponse response;

    public View(HttpServlet servlet, HttpServletRequest request,
            HttpServletResponse response) {
        this.servlet = servlet;
        this.application = servlet.getServletContext();
        this.request = request;
        this.response = response;

        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
    }

    public void display(String path) {
        path = "WEB-INF/view/" + path;
        try {
            if (new File(application.getRealPath(path)).exists()) {
                request.getRequestDispatcher("/" + path).include(request,
                        response);
            } else {
                response.getWriter().print("文件'" + path + "'不存在");
            }
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    public void display(String path, DataList<?> datalist) {
        request.setAttribute("list", datalist);
        display(path);
    }

    public void displayMap(String path, Object... key_val) {
        if (key_val.length % 2 == 0) {
            for (int i = 0; i < key_val.length; i+=2) {
                request.setAttribute((String) key_val[i], key_val[i+1]);
            }
            display(path);
        } else {
            displayMap(path, "title", "displayMap参数错误",
                    "msg", "displayMap 的 key_val 只能是偶数个");
        }
    }
    public void display(String path, String msg) {
        request.setAttribute("msg", msg);
        display(path);
    }

    public void show(String content) {
        try {
            response.getWriter().print(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void print(String content) {
        show(content);
    }

    public void println(String content) {
        show(content + "<br/>");
    }

    public void sendRedirect(String path) {
        try {
            response.sendRedirect(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
